//
//  TabView.m
//  陪你傻笑
//
//  Created by 宗镇荣 on 16/2/15.
//  Copyright © 2016年 zzr. All rights reserved.
//

#import "TabView.h"
#import "CommonDefin.h"
#import "UIColor+NewYear.h"

@interface TabView()

@property (nonatomic, assign) NSInteger lastBtnTag;

@end

@implementation TabView

// 重写setter方法
- (void)setTitleArray:(NSArray *)titleArray {

    //按钮的间距和宽度和高度
    CGFloat kBtnSpace = 9;
    CGFloat kBtnWidth = (kScreenWidth-kBtnSpace*(titleArray.count))/titleArray.count;
    CGFloat kBtnHeight = self.frame.size.height;
    
    //循环创建按钮
    for (int i = 0; i < titleArray.count; i++) {
        UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(kBtnSpace+ i*(kBtnWidth+kBtnSpace), 0, kBtnWidth, kBtnHeight)];
        [btn setTitle:titleArray[i] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        
        //设置选中状态的文字颜色
        [btn setTitleColor:[UIColor getTopicColor] forState:UIControlStateSelected];
        
        btn.tag = 100+i;
        
        btn.titleLabel.adjustsFontSizeToFitWidth = YES;
        
        [btn addTarget:self action:@selector(onClick:) forControlEvents:UIControlEventTouchUpInside];
        
        if (i == 0) {
            btn.selected = YES;
            _lastBtnTag = i+100;
        }
        [self addSubview:btn];
    }
}

- (void)onClick:(UIButton *)btn {

    // 1. 把上一次选中的状态selected = NO;
    UIButton *lastBtn = [self viewWithTag:_lastBtnTag];
    lastBtn.selected = NO;
    
    // 2. 把选中的按钮的状态selected = YES;
    btn.selected = YES;
    
    // 3. 更新lastBtnTag得值
    _lastBtnTag = btn.tag;
    
    // 调用协议方法
    if (_delegate && [_delegate respondsToSelector:@selector(tabBtn:)]) {
        [_delegate tabBtn:btn.tag - 100];
    }else {
    
        NSLog(@"没有设置队列或者没有带来没有实现协议方法");
    }
}

- (void)resetBtnStatus:(NSInteger)btnTag {

    // 1. 把上一次选中的状态selected = NO;
    UIButton *lastBtn = [self viewWithTag:_lastBtnTag];
    lastBtn.selected = NO;
    
    // 2. 把传来的按钮的状态selected = YES
    UIButton *selectBtn = [self viewWithTag:btnTag];
    selectBtn.selected = YES;
    // 3. 更新lastBtnTag的值
    _lastBtnTag = btnTag;
}

@end
